package com.qidian.server.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.qidian.common.Globals;
import com.qidian.common.MessageStatus;
import com.qidian.common.beans.AccountBean;
import com.qidian.common.beans.ClientBean;
import com.qidian.common.beans.MessageBean;
import com.qidian.common.beans.UserBean;
import com.qidian.server.MServer;
import com.qidian.server.Status;
import com.qidian.util.PageList;

public class ClientServlet extends HttpServlet
{

	/**
	 * 
	 * 
	 */
	private static final long serialVersionUID = 9056245378746859637L;
	private static final Logger logger = Logger.getLogger(ClientServlet.class.getName()) ;
	private static final MServer mserver = MServer.getInstance() ;
	
	public void init()
	{
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		Status status = Status.OK ;
		String actionType = request.getParameter(ServletConstants.arg_action_type) ;
		response.setCharacterEncoding("utf8");
		try
		{
    		if ("sendAnswers".equalsIgnoreCase(actionType))
    			status = sendAnswers(request,response) ;
    		else if ("sendAnswer".equalsIgnoreCase(actionType))
    			status = sendAnswer(request,response) ;    		
    		else if ("getCount".equalsIgnoreCase(actionType))
    		    status = getCount(request,response) ;
    		else if ("getTransMsg".equalsIgnoreCase(actionType))
    			status = getTransMsg(request,response) ;
    		else if ("login".equalsIgnoreCase(actionType))
    			status = login(request,response) ;
    		else if ("logout".equalsIgnoreCase(actionType))
    			status = logout(request,response) ;
    		else if ("getMsg".equalsIgnoreCase(actionType))
    			status = getMsg(request,response);
    		else if ("queryWrongAnswerRecord".equalsIgnoreCase(actionType))
    			status = queryWrongAnswerRecord(request,response) ;
    		else if ("getQueryWrongAnswerRecordDlg".equalsIgnoreCase(actionType))
    			status = getQueryWrongAnswerRecordDlg(request,response) ;
    		else if ("reportWrongAnswers".equalsIgnoreCase(actionType))
    			status = reportWrongAnswers(request,response) ;
    		else if ("reportWrongAnswer".equalsIgnoreCase(actionType))
    			status = reportWrongAnswer(request,response) ;
    		else //默认登录
    		{
    		    status = Status.INVALID_ARGUMENT ;
    	        RequestDispatcher disp = request.getRequestDispatcher("/modules/client/login.html") ;
    	        disp.forward(request, response) ;
    	        return ;
    		}
		}
		catch(Exception e)
		{
		    e.printStackTrace() ;
		    logger.error(e.getMessage()) ;
		    status = Status.OTHER_ERROR ;
		}
		if (status != Status.OK)
		{
            response.setCharacterEncoding("utf8") ;
            response.getWriter().write(status.statusCode.toString()) ;
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		Status status = Status.OK ;
		String actionType = request.getParameter(ServletConstants.arg_action_type) ;
		response.setCharacterEncoding("utf8");
		try
		{
    		
    		if ("sendAnswer".equalsIgnoreCase(actionType))
    			status = sendAnswer(request,response) ;
    		else if ("sendAnswers".equalsIgnoreCase(actionType))
    			status = sendAnswers(request,response) ;
    		else
    			status = Status.INVALID_VALUE ;
		}
		catch(Exception e)
		{
		    e.printStackTrace() ;
		    logger.error(e.getMessage()) ;
		    status = Status.OTHER_ERROR ;
		}
		if (status != Status.OK)
		{
            response.setCharacterEncoding("utf8") ;
            response.getWriter().write(status.statusCode.toString()) ;
		}
	}
	private Status getTransMsg(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
        String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
        String strMsgCount = request.getParameter(ServletConstants.arg_msg_count) ;
        String strTransType = request.getParameter(ServletConstants.arg_trans_type) ;
        String password = request.getParameter(ServletConstants.arg_password) ;
//        System.out.println(request.getQueryString()) ;
        StringBuffer result = new StringBuffer(64) ;
        Status status = mserver.c2s_getTransMsg(strClientId,password, strMsgCount,strTransType,result) ;
        if (status == Status.OK)
        {
			response.getWriter().write(result.toString()) ;
        }
        return status ;
	}

	/**
	 *  返回多个答案
	 * @throws IOException 
	 * 
	 * */
	private Status sendAnswers(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String answers = request.getParameter(ServletConstants.arg_answers) ;
		String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
		String strPassword = request.getParameter(ServletConstants.arg_password) ;
		if (answers == null || strClientId == null || strPassword == null)
			return Status.INVALID_ARGUMENT ;
		long clientId = Long.parseLong(strClientId) ;
		Status status = mserver.c2s_sendAnswers(answers, clientId, strPassword) ;
		if (status == Status.OK)
			response.getWriter().write(status.statusCode.toString()) ;
		
		return status ;
	}
	/**
	 *  返回单个答案
	 * @throws IOException 
	 * 
	 * */
	private Status sendAnswer(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
//		String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
		String answer = request.getParameter(ServletConstants.arg_answer) ;
		String strMsgId = request.getParameter(ServletConstants.arg_msg_id) ;
		String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		long clientId = Long.parseLong(strClientId) ;
//		System.out.println(strMsgId+":"+java.net.URLDecoder.decode(answer,"UTF-8")) ;
		Status status = mserver.c2s_sendAnswer(strMsgId,answer,clientId,password) ;
		if (status == Status.OK)
			response.getWriter().write(status.statusCode.toString()) ;
		
		return status ;
	}	

    /**
     * 申请图片信息
     * @throws IOException 
     * 
     * @throws ServletException 
     * 
     * */
    private Status getMsg(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
        String strMsgCount = request.getParameter(ServletConstants.arg_msg_count) ;
        String strKey = request.getParameter(ServletConstants.arg_key) ;
        String strPassword=request.getParameter(ServletConstants.arg_password) ;
        
        StringBuffer result = new StringBuffer(64) ;
        Status status = mserver.c2s_getMsg(strClientId, strMsgCount,strPassword,strKey,result) ;
        if (status == Status.OK)
        {
			response.getWriter().write(result.toString()) ;
        }
        
        return status ;
    }	
	
	/**
	 *  获取计数信息
	 * 
	 * */
	private Status getCount(HttpServletRequest request , HttpServletResponse response)
	{
	    String strClientId = request.getParameter(ServletConstants.arg_client_id) ;
	    StringBuffer result = new StringBuffer(512) ;
	    
	    Status status = mserver.c2s_getCount(strClientId, result) ;
	    if (status == Status.OK)
	    try
        {
	    	response.setCharacterEncoding("utf8");
            response.getWriter().write(result.toString()) ;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            logger.error(e.getMessage()) ;
            status =  Status.OTHER_ERROR ;
        }

	    return status ;
	}
	
	/**
	 * 单个提交误报
	 * 
	 * */
	private Status reportWrongAnswer(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String msgId = request.getParameter(ServletConstants.arg_msg_id) ;
		Status status = mserver.c2s_reportWrongAnswer(msgId) ;
		if (status == Status.OK)
			response.getWriter().write(status.toString()) ;
		return status ;
	}
	
	/**
	 * 批量提交误报
	 * 
	 * */
	private Status reportWrongAnswers(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String msgIds = request.getParameter(ServletConstants.arg_msg_ids) ;
		return Status.OK ;
	}
	
	private Status getQueryWrongAnswerRecordDlg(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<div nowrap>") ;
                        	result.append("<p>");
                        	result.append("<label>题&nbsp;&nbsp;&nbsp;&nbsp;号：</label><input id=msgId type=text class=textSmall maxlength=48/>");
                          	result.append("<label>IP：</label><input id=ip type=text class=textMedium maxlength=15/>");
                        	result.append("<p><label>用&nbsp;户&nbsp;名&nbsp;&nbsp;：</label><input id=userName type=text class=textMedium maxlength=20/>");
                        	result.append("<label>子账号：</label><input id=account type=text class=textLong maxlength=48/>");
                        	result.append("<input class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" type=\"submit\" value=\"提交查询\" onclick=\"onQueryWrongAnswerRecord();return false;\"/>");
                        	result.append("</p><p>");
                        	result.append("<label>项目类型：</label><input id=gameType type=text class=textSmall maxlength=4/>");
                        	result.append("<label>发送时间：</label><input id=sendDate type=text class=textDate value=").append(new Date(System.currentTimeMillis())).append(" />") ;
                        	result.append("从&nbsp;&nbsp;<input id=minSendTime type=text class=textSmall value=00:00:00 />") ;
                        	result.append("到&nbsp;&nbsp;<input id=maxSendTime type=text class=textSmall value=23:59:59 />") ;
                    		result.append("</p>");
                result.append("</div>") ;
        result.append("</form>") ;
	    try
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}
	
	/**
	 * 查询错题记录
	 * 
	 * */
	private Status queryWrongAnswerRecord(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
//		String clientName = request.getParameter(ServletConstants.arg_client_name) ;
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
//		String strStatus = request.getParameter(ServletConstants.arg_status) ;
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		String strMsgId = request.getParameter(ServletConstants.arg_msg_id) ;
		String strMinSendTime = request.getParameter(ServletConstants.arg_min_send_time) ;
		String strMaxSendTime = request.getParameter(ServletConstants.arg_max_send_time) ;
		
		int gameType = Integer.MIN_VALUE  ;
		int status = MessageStatus.WRONG.status;
		long msgId = Long.MIN_VALUE ;
		long minSendTime = -1 ;
		long maxSendTime = -1 ;
		String clientName = ((ClientBean)request.getSession().getAttribute(ServletConstants.s_attr_client)).getClientName() ;
		if (account == null || strGameType == null
				 || strPageNo == null || strMsgId == null || strMinSendTime == null || strMaxSendTime == null)
			return Status.INVALID_ARGUMENT ;
		
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
			if (strGameType != null && strGameType.length() > 0)
				gameType = Integer.parseInt(strGameType) ;
			if (strMsgId != null && strMsgId.length() > 0)
				msgId = Long.parseLong(strMsgId) ;
			if (strMinSendTime != null && strMinSendTime.length() > 6)
				minSendTime = Long.parseLong(strMinSendTime) ;
			if (strMaxSendTime != null && strMaxSendTime.length() > 6)
				maxSendTime = Long.parseLong(strMaxSendTime) ;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getAnswerRecordListForSuper(pageNo,
							msgId,account, clientName, gameType, status, null, null,
							minSendTime,maxSendTime,-1L) ;
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;

    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
//				result.append("<td>题号</td>");
				result.append("<td>图片</td>");
				result.append("<td>用户名/子账号ID/题号/处理速度/项目类型</td>");
//				result.append("<td>发送时间/IP/处理速度</td>");
				result.append("<td>答案</td>");
				result.append("<td class=action>操作</td>");
			result.append("</tr>");
			MessageBean message ;
			Timestamp temp = new Timestamp(System.currentTimeMillis()) ;
		
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				message = (MessageBean)pageList.getList().get(i) ; 
				temp.setTime(message.getReceiveTime()) ;
//				ClientBean client = Globals.getClientBuffer().getClient(message.getClientId());
				result.append("<tr>");
	                UserBean user = Globals.getUserBuffer().getById(message.getUserId()) ;
	                AccountBean accountBean = Globals.getAccountBuffer().get(message.getAccountId()) ;
	                result.append("<td><img  width=240 height= 180 src=");
					if (message.getContent() == null)
						result.append("\"\"") ;
					else
					{
						String path = Globals.getUploadDirAbsolutePath()+message.getId() ;
						File file = new File(path);
						if(!file.exists())
						{	
							file.createNewFile() ;
							FileOutputStream fos = new FileOutputStream(file);
							fos.write(message.getContent()) ;
							fos.close() ;
						}
						path = Globals.getUploadRelativePath()+message.getId();
						result.append(path) ;
					}
	                result.append(" ></img></td>") ;
	                result.append("<td>").append(user.getUserName()).append("/").append(message.getAccountId())
	                	.append("/").append(message.getId()).append("/") ;
					if(message.getAnswerTime()>0)
						result.append((message.getAnswerTime()-message.getReceiveTime())/1000) ;
					else
						result.append("-");
					result.append("/").append(message.getGameType());
					result.append("</td>");
					result.append("<td>").append(message.getAnswer()==null?"-":message.getAnswer())
						.append("</td>");
//					result.append("<td >").append(message.getAccountId()).append("</td>");
					result.append("<td class=action>") ;
					result.append("<a href=\"#\" class=\"view\" onclick=\"onReportWrongAnswer('").append(message.getId())
					.append("'); return false;\">提交误报</a>") ;
					result.append("</td>");

				
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryWrongAnswerRecord();"));
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;	
	}
	
	// 登陆
	private Status login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		String type = request.getParameter(ServletConstants.arg_type) ;
		String key = request.getParameter(ServletConstants.arg_key);
		if (userName == null || password == null)
			return Status.INVALID_ARGUMENT ;
		else
		{
			ClientBean client = mserver.c2s_login(userName, password,key) ;
			if (client != null)
			{
				request.getSession().setAttribute(ServletConstants.s_attr_key, key);
				request.getSession().setAttribute(ServletConstants.s_attr_client, client) ;
				if ("report".equalsIgnoreCase(type))
				{
					RequestDispatcher dispatch = request.getRequestDispatcher("client_index.html") ;
					dispatch.forward(request, response) ;
				}
				else
				{
					RequestDispatcher dispatch = request.getRequestDispatcher("modules/client/new_client.jsp") ;
					dispatch.forward(request, response) ;
				}
			}
			else
				return Status.INVALID_USERNAME_OR_PASSWORD ;
		}
		return  Status.OK;
	}
	/**
	 *  注销
	 * @throws IOException 
	 * @throws ServletException 
	 * 
	 * */
	private Status logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String clientId = request.getParameter(ServletConstants.arg_client_id) ;
		String userName = request.getParameter(ServletConstants.arg_user_name) ;
		String password = request.getParameter(ServletConstants.arg_password) ;
		String type = request.getParameter(ServletConstants.arg_type) ;
	
		if ("report".equalsIgnoreCase(type))
		{
	        RequestDispatcher disp = request.getRequestDispatcher("/modules/client/login.html") ;
	        disp.forward(request, response) ;
	        return Status.OK ;
		}
		
		Status status = mserver.c2s_logout(clientId,userName,password) ;
		if (status == Status.OK)
			response.getWriter().write(status.statusCode.toString()) ;

		return status ;
	}
	
	public void destroy()
	{
		
	}
}
